var assert = require('assert');
var logger = using('easynode.framework.Logger').forFile(__filename);
var GenericObject = using('easynode.GenericObject');
var ActionResult = using('easynode.framework.mvc.ActionResult');
var utility = require('utility');
var HTTPUtil = using('easynode.framework.util.HTTPUtil');
var BeanFactory = using('easynode.framework.BeanFactory');
var thunkify = require('thunkify');
var md5 = require('md5');
var randomstring=require('randomstring');


(function () {
        /**
         * Class AuthController
         *
         * @class #NAMESPACE#.AuthController
         * @extends easynode.GenericObject
         * @since 0.1.0
         * @author zlbbq
         * */
        class AuthController extends GenericObject {
                /**
                 * 构造函数。
                 *
                 * @method 构造函数
                 * @since 0.1.0
                 * @author zlbbq
                 * */
                constructor() {
                        super();
                        //调用super()后再定义子类成员。
                        this.bookshelf = null;                          //IoC injection
                        this.cache = null;
                        this.wxAPI=null;
                        this.wxOauth=null;
                        this.wxPayMent=null;
                        this.util=null;
                }


                /**
                 * @api {post} /api/checkin 开发模式接入校验
                 * @apiName auth
                 * @apiGroup wechat
                 *
                 * @apiParam {String} echostr
                 * @apiParam {String} timestamp
                 * @apiParam {String} nonce
                 * @apiParam {String} signature
                 *
                 * @apiSuccess {Number} code 返回码，0 -> 成功
                 * @apiSuccess {Object} result API处理结果
                 * @apiSuccess {String} msg 对应于返回码的文本消息
                 * */
                auth() {
                        var me = this;
                        return function * () {
                                // this.validator.check('deviceId').necessary().end();
                                //this.validator.check('money').necessary().isInt().min(0).end();
                                //this.validator.check('simExpire').necessary().date().end();

                               var api= me.wxAPI.getAPI();
                             //   logger.error(JSON.stringify(api));
                                if (this.validator.isValid()) {
                                        var echostr=this.p('echostr');

                                        logger.error('echostr:'+echostr);
                                        return echostr;
                                }
                        };
                }


                /**
                 * @api {get} /api/getJsConfig 获取JSSDK签名
                 * @apiDescription 获取JSSDK签名
                 * @apiName getJsConfig
                 * @apiGroup wechat
                 *
                 * @apiParam {String} url 需要签名的url
                 *
                 * @apiSuccess {String} jsapi_ticket JSSDK ticket
                 * @apiSuccess {String} nonceStr 随机码
                 * @apiSuccess {String} timestamp 时间戳
                 * @apiSuccess {String} url 签名的url
                 * @apiSuccess {String} appId 公众号 appId
                 *
                 */

                getJsConfig()
                {
                        var me = this;
                        return function * () {
                                 this.validator.check('url').necessary().end();
                                if (this.validator.isValid()) {
                                        var param = {
                                                debug: false,
                                                jsApiList: me.util.constants.jsApiList,
                                                url: this.p('url')
                                        };
                                        var config= yield me.wxAPI.getJsConfig(param);
                                        logger.error(JSON.stringify(config));
                                        return ActionResult.createSuccessResult(config)
                                }
                        };
                }


                /**
                 * @api {post} /api/getPaymentParams 统一下单
                 * @apiDescription 统一下单
                 * @apiName getPaymentParams
                 * @apiGroup wechat
                 *
                 * @apiParam {String} url 需要签名的url
                 *
                 * @apiSuccess {String} prepay_id 预订单编号
                 *
                 */
                getPaymentParams()
                {
                        var me = this;
                        return function * () {
                                if (this.validator.isValid()) {
                                        //for test
                                        var order={
                                                openid: '微信用户 openid',
                                                body: '公众号支付测试',
                                                detail: '公众号支付测试',
                                                out_trade_no: '20150331'+Math.random().toString().substr(2, 10),
                                                total_fee: 1,
                                                spbill_create_ip: '192.168.2.210',
                                                notify_url: 'http://wxpay_notify_url'
                                        }
                                        return  yield me.wxPayMent.getPaymentParams(order);
                                }
                        };

                }
                /**
                 * @api {post} /api/useWXCallback 接受支付结果通知
                 * @apiDescription 接受支付结果通知
                 * @apiName useWXCallback
                 * @apiGroup wechat
                 *
                 */

                useWXCallback()
                {
                        var me = this;
                        return function * () {
                                if (this.validator.isValid()) {

                                        var successMessage=util.buildXML({ xml:{ return_code:'SUCCESS' } });
                                        var errorMessage=util.buildXML({ xml:{ return_code:'FAIL' } });
                                        var msg=yield me.wxPayMent.useWXCallback();
                                        //todo  判断成功还是失败,进行对应的业务逻辑

                                        return successMessage;
                                }
                        };

                }
                /**
                 * @api {post} /api/receiveFromServer 开发模式下从后台接收数据
                 * @apiDescription 开发模式下从后台接收数据
                 * @apiName receiveFromServer
                 * @apiGroup wechat
                 *
                 */
                receiveFromServer() {
                        var me = this;
                        return function * () {
                                // this.validator.check('deviceId').necessary().end();
                                //this.validator.check('money').necessary().isInt().min(0).end();
                                //this.validator.check('simExpire').necessary().date().end();
                                if (this.validator.isValid()) {

                                        return '';
                                }
                        };
                }
                /**
                 * @api {post} /api/getAuthorizeURL 获取授权链接
                 * @apiDescription 获取授权链接
                 * @apiName getAuthorizeURL
                 * @apiGroup wechat
                 *
                 * @apiParam {String} redirectUrl 跳转到的URL*
                 *
                 * @apiSuccess {String} authorizeUrl  授权链接
                 */

                getAuthorizeURL()
                {
                        var me = this;
                        return function*()
                        {
                                this.validator.check('redirectUrl').necessary().end();
                                if(this.validator.isValid())
                                {
                                        var state = md5(Date.now().toString() + randomstring.generate(4).toString());
                                        var snsapiType = 'snsapi_base';
                                        var url=me.wxOauth.getAuthorizeURL(this.p('redirectUrl'), state,snsapiType);
                                        return ActionResult.createSuccessResult(url);
                                }
                        }
                }



                /**
                 * @api {post} /api/getOpenId 获取openid
                 * @apiDescription 获取授权链接
                 * @apiName getOpenId
                 * @apiGroup wechat
                 *
                 * @apiParam {String} code 微信服务器返回的code *
                 *
                 * @apiSuccess {String} openid 用户关注微信号的唯一标示
                 *
                 */

                getOpenId()
                {
                        var me = this;
                        return function*()
                        {
                                this.validator.check('code').necessary().end();
                                if(this.validator.isValid())
                                {
                                        var token;
                                        try
                                        {
                                                 token= yield me.wxOauth.getAccessToken(this.p('code'));
                                        }
                                        catch(e)
                                        {
                                                logger.error(e);
                                                return ActionResult.createAppError(me.util.constants.CODE_OPENID_ERROR)
                                        }

                                        return   ActionResult.createSuccessResult(token.data.openid);
                                }
                        }
                }


                getClassName() {
                        return EasyNode.namespace(__filename);
                }
        }

        module.exports = AuthController;
})();